﻿#include "IM_FriendMap.h"

#include "IM_Account.h"

IM_FriendMap::IM_FriendMap(const std::string & number ,IM_DataInterface * data_interface)
	:m_data_interface(data_interface)
	,m_munber(number)
{
	std::vector<std::string > vec;
	m_data_interface->getFriendVector(m_munber, vec);
	IM_AccountServer * p = IM_AccountServer::getInstance();
	for (auto v:vec)
	{
		auto a=p->findAccount(v);
		if (a!=nullptr)
		{
			m_friends_map.emplace(std::move(v), a);
		}
		else
		{
			DEBUG("出错 发生未初始化的 acount \n");
		}
	}
}

IM_FriendMap::~IM_FriendMap()
{
	m_data_interface = nullptr;
	m_friends_map.clear();
	
}

/*bool IM_FriendMap::init(IM_AccountServer * s, const std::vector<std::string>& friend_vec)
{
	for (auto v:friend_vec)
	{
		IM_Account * a=s->findAccount(v);
		if (a)
		{
			m_friends_map.emplace(v, a);
		}
		else
		{
			DEBUG("查询好友失败 ！ \n");
		}
	}
}*/

IM_Account * IM_FriendMap::getAccountByNumber(const std::string& munber)
{
	IM_Account * r = nullptr;

	m_mutex.lock();
	std::map<std::string ,IM_Account*>::iterator   f = m_friends_map.find(munber);
	if (f!=m_friends_map.end())
	{
		r = (*f).second;
	}
	m_mutex.unlock();
	if (!r)
	{
		DEBUG("查找账户失败  ，返回 null \n");
	}
	return r;
}

bool IM_FriendMap::addFriend(IM_Account * ac, const std::string& number)
{
	if (ac==nullptr)
	{
		return false;
	}
	m_mutex.lock();
	m_friends_map.emplace(number, ac);
	m_mutex.unlock();
	return true;
}

int IM_FriendMap::removeFriend(const std::string & number)
{
	int r = 0;

	m_mutex.lock();
	std::map<std::string, IM_Account *>::iterator iter = m_friends_map.find(number);
	if (iter!=m_friends_map.end())
	{
		m_friends_map.erase(iter);
	}
	else
	{
		r = -1;
	}
	m_mutex.unlock();

	return r;
}

void IM_FriendMap::print_all_frined()
{
#ifdef _DEBUG
	printf("好友列表:\n");
	for (auto v : m_friends_map)
	{
		v.second->print_infor();
	}

#endif // _DEBUG
}

const std::map<std::string, IM_Account *> & IM_FriendMap::get_map()
{
	return m_friends_map;
}
